package com.herokuapp.zhachuang;

import com.herokuapp.zhachuang.service.HttpUtilities;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.herokuapp.zhachuang.entity.UserProfile;
import com.herokuapp.zhachuang.service.Servant;
import com.herokuapp.zhachuang.service.UserProfileService;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.model.ReplyMessage;
import com.linecorp.bot.model.action.PostbackAction;
import com.linecorp.bot.model.event.Event;
import com.linecorp.bot.model.event.MessageEvent;
import com.linecorp.bot.model.event.message.ImageMessageContent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import com.linecorp.bot.model.event.source.Source;
import com.linecorp.bot.model.event.source.UserSource;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.model.message.quickreply.QuickReply;
import com.linecorp.bot.model.message.quickreply.QuickReplyItem;
import com.linecorp.bot.spring.boot.annotation.EventMapping;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * When an event occurs, such as when a user adds your LINE Official Account as
 * a friend or sends a message, the LINE Platform sends an HTTPS POST request to
 * the webhook URL (bot server).
 *
 * @author P-C Lin (a.k.a 高科技黑手)
 */
@com.linecorp.bot.spring.boot.annotation.LineMessageHandler
public class LineMessageHandler {

	private static final Logger LOGGER = LoggerFactory.getLogger(LineMessageHandler.class);

	private static final String LINE_BOT_CHANNEL_TOKEN = System.getenv("LINE_BOT_CHANNEL_TOKEN");

	@Autowired
	private LineMessagingClient lineMessagingClient;

	@Autowired
	private UserProfileService userProfileService;

	@EventMapping
	public void handleEvent(Event event) throws JsonProcessingException {
		LOGGER.info(
			getClass().getName() + ".handleEvent(\n\t{}\n);\n{}",
			event
		);
	}

	@EventMapping
	public void handleImageMessageEvent(MessageEvent<ImageMessageContent> event) throws Exception {
		LOGGER.info(
			getClass().getName() + ".handleImageMessageEvent(\n\t{}\n);\n{}",
			event
		);

		CloseableHttpClient httpClient = HttpUtilities.httpClient();
		HttpGet httpGet = new HttpGet(
			String.format(
				"https://api-data.line.me/v2/bot/message/%s/content",
				event.getMessage().getId()
			)
		);
		httpGet.addHeader(
			"Authorization",
			String.format(
				"Bearer %s",
				LINE_BOT_CHANNEL_TOKEN
			)
		);
		CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
		if (200 == httpResponse.getStatusLine().getStatusCode()) {
			HttpEntity httpEntity = httpResponse.getEntity();
			if (Objects.isNull(httpEntity)) {
				LOGGER.info("幹，是空的");
			} else {
				InputStream inputStream = httpEntity.getContent();
				LOGGER.info(
					"這裏\n{}",
					IOUtils.toString(
						inputStream,
						StandardCharsets.UTF_8
					).length()
				);
				inputStream.close();
			}
			httpResponse.close();
		} else {
			LOGGER.info("幹，不是二百");
		}
		httpClient.close();
	}

	@EventMapping
	public void handleTextMessageEvent(MessageEvent<TextMessageContent> event) throws Exception {
		LOGGER.info(
			getClass().getName() + ".handleTextMessageEvent(\n\t{}\n);\n{}",
			event
		);

		String replyToken = event.getReplyToken();

		Source source = event.getSource();
		if (!(source instanceof UserSource)) {
			lineMessagingClient.replyMessage(
				new ReplyMessage(
					replyToken,
					new TextMessage(
						"非 UserSource"
					)
				)
			);
			return;
		}

		source = (UserSource) source;
		String senderId = source.getSenderId();
		String userId = source.getUserId();

		TextMessageContent textMessageContent = event.getMessage();
		String text = textMessageContent.getText();

		if (text.matches("^09\\d{8}$")) {
			if (userProfileService.existsByCellular(text)) {
				lineMessagingClient.replyMessage(
					new ReplyMessage(
						replyToken,
						new TextMessage(
							textMessageContent.getText()
						)
					)
				);
			} else {
				UserProfile userProfile = new UserProfile();
				userProfile.setCellular(text);
				userProfile = userProfileService.persist(userProfile);

				lineMessagingClient.replyMessage(
					new ReplyMessage(
						replyToken,
						new TextMessage(
							String.format(
								"```%n%s%n```註冊了 %s 用戶",
								Servant.PRETTY_PRINTER.
									writeValueAsString(
										userProfile
									),
								text
							)
						)
					)
				);
			}
		} else if (text.matches("^09\\d{8}\\+\\d{2,}$")) {
			lineMessagingClient.replyMessage(
				new ReplyMessage(
					replyToken,
					new TextMessage(
						String.format(
							"配對 %s%nsender = %s%nuser = %s",
							textMessageContent.getText(),
							senderId,
							userId
						)
					)
				)
			);
		} else if (text.matches("^\\*09\\d{8}$")) {
			lineMessagingClient.replyMessage(
				new ReplyMessage(
					replyToken,
					new TextMessage(
						String.format(
							"新增 %s%nsender = %s%nuser = %s",
							textMessageContent.getText(),
							senderId,
							userId
						),
						QuickReply.
							builder().
							item(
								QuickReplyItem.
									builder().
									action(
										PostbackAction.
											builder().
											data("data").
											displayText("displayText").
											label("label").
											build()
									).
									build()
							).
							build()
					)
				)
			);
		} else {
			lineMessagingClient.replyMessage(
				new ReplyMessage(
					replyToken,
					new TextMessage(
						textMessageContent.getText()
					)
				)
			);
		}

		LOGGER.debug(
			"用戶\n{}",
			lineMessagingClient.
				getProfile(
					userId
				).
				get()
		);
	}
}
